//
//  YJCDownloadController.m
//  ProjectDemo
//
//  Created by IOS3 on 2019/1/9.
//  Copyright © 2019 IOS3. All rights reserved.
//

#import "YJCDownloadController.h"
#import "TDModel.h"
#import "TDCell.h"
#import "SODownloader+TDManager.h"


@interface YJCDownloadController ()
@property (nonatomic, copy) NSArray *downloadURLs;

@property (nonatomic, copy) NSArray<SODownloadItem> *models;
@end

@implementation YJCDownloadController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 50;
    
    NSString *cellName = NSStringFromClass(TDCell.class);
    [self.tableView registerNib:[UINib nibWithNibName:cellName bundle:nil] forCellReuseIdentifier:cellName];
    [[SODownloader sharedInstance] downloadItems:self.models];
    
}






- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.models.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TDCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(TDCell.class) forIndexPath:indexPath];
    TDModel *model = self.models[indexPath.row];
    cell.model = model;

    return cell;
}







- (NSArray *)models {
    if (!_models) {
        NSMutableArray *marr = [NSMutableArray array];
        for (NSString *url in self.downloadURLs) {
            TDModel *model = [[TDModel alloc] initWithURLString:url];
            [marr  addObject:model];
        }
        _models = marr.copy;
    }
    return _models;
}


- (NSArray *)downloadURLs {
    if (!_downloadURLs) {
        NSMutableArray *marr = [NSMutableArray array];
        
        NSString *jsonPath = [NSBundle.mainBundle pathForResource:@"downloadSource" ofType:@"json"];
        NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
        id obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
        if ([obj isKindOfClass:NSArray.class]) {
            NSArray *array = (NSArray *)obj;
            for (NSString *urlString in array) {
                [marr addObject:urlString];
            }
        }
        _downloadURLs = marr.copy;
    }
    return _downloadURLs;
}

@end
